package com.mz.ozy.activity.find;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jaeger.library.StatusBarUtil;
import com.mz.ozy.R;
import com.mz.ozy.activity.assets.ExchangeActivity;
import com.mz.ozy.activity.home.ExchangeDetailActivity;
import com.mz.ozy.adapter.FriendDynamicsAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.DynamicListBean;
import com.mz.ozy.bean.DynamicsBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.HomePageBean;
import com.mz.ozy.bean.MyIntegralBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.bean.ReplyBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.model.FollowModel;
import com.mz.ozy.mvp.presenter.ExpertDetailPresenter;
import com.mz.ozy.mvp.view.ExpertDetailContract;
import com.mz.ozy.utils.AndroidBug5497Workaround;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.EmojiUtils;
import com.mz.ozy.utils.KeyboardChangeListener;
import com.mz.ozy.utils.LocationHelper;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.BlackListDialog;
import com.mz.ozy.widget.dialog.BottomPhotoDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.mz.ozy.utils.KeyboardChangeListener.KeyBoardListener;

public class HomePageActivity extends BaseActivity<ExpertDetailContract.View, ExpertDetailPresenter> implements ExpertDetailContract.View, KeyBoardListener {
    public static final String USER_UID = "USER_UID";

    @BindView(R.id.rv_friend_dynamics)
    RecyclerView mRvFriendDynamics;
    @BindView(R.id.rl_empty)
    RelativeLayout mRlEmpty;
    @BindView(R.id.tv_empty)
    TextView mTvEmpty;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_friend_praised)
    TextView mTvFriendPraised;
    @BindView(R.id.tv_friend_praise)
    TextView mTvFriendPraise;
    @BindView(R.id.tv_friend_comment)
    TextView mTvFriendComment;
    @BindView(R.id.tv_friend_nickname)
    TextView mTvFriendName;
    @BindView(R.id.tv_friend_address)
    TextView mTvFriendAddress;
    @BindView(R.id.iv_friend_head)
    ImageView mIvFriendHead;
    @BindView(R.id.iv_home_page_backgroud)
    ImageView mIvHomePageBackgroud;
    @BindView(R.id.et_dynamics_comment_input)
    EditText mEtCommentInput;
    @BindView(R.id.ll_send_comment)
    LinearLayout mLlSendComment;
    @BindView(R.id.tv_comment_send)
    TextView mTvSendComment;

    private int tag;
    private int page;
    private FriendDynamicsAdapter mFriendDynamicsAdapter;
    private List<DynamicsBean> mDynamicsBeans = new ArrayList<>();
    private String mUid;
    private int dynamicType = 1;   //1 全部动态 2 获赞  3 赞过
    private String nickname;

    private ReplyBean mCurReply;
    private String mHostName;
    private int mDynamicsID;
    private KeyboardChangeListener mKeyboardChangeListener;
    private InputMethodManager manager;
    private String isBlack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        StatusBarUtil.setTranslucentForImageViewInFragment(HomePageActivity.this, 20, null);
        AndroidBug5497Workaround.assistActivity(this);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initTitle();
        setTitleBarMargin();
        mUid = getIntent().getStringExtra("id");
        manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        initKeyBoardListener();
        initRefreshLayout();
        initView();
        initEvents();
//        mRefreshLayout.autoRefresh();
        requestDataForNetwork();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        if (event.getCode() == Constants.EventCode.DELETE_DYNAMICS
                || event.getCode() == Constants.EventCode.REPLY_DYNAMICS) {
            requestDataForNetwork();
        }
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    public void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    private void requestDataForNetwork() {
        tag = 0;
        page = 1;
        mPresenter.queryHomePage(this, mUid, page, dynamicType);
    }

    private void initEvents() {
        rightImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPhotoDialog();
            }
        });
        mFriendDynamicsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                DynamicsBean item = mFriendDynamicsAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.item_dynamics_view: {
                        mFriendDynamicsAdapter.setCollPosition(position);
                        Intent intent = new Intent(HomePageActivity.this, DynamicDetailActivity.class);
                        intent.putExtra(DynamicDetailActivity.DYNAMICS_ID, item.getId());
                        intent.putExtra(DynamicDetailActivity.DYNAMICS_UID, mUid);
                        intent.putExtra(DynamicDetailActivity.DYNAMICS_CID, item.getTid() + "");
                        startActivity(intent);
                        break;
                    }
                    case R.id.ll_friend_dynamics_like: {
                        mFriendDynamicsAdapter.setCollPosition(position);
                        mPresenter.followDynamics(HomePageActivity.this, item.getId(), FollowModel.DYNAMIC_TYPE);
                        break;
                    }
                    case R.id.ll_friend_dynamics_comment: {
                        mDynamicsID = item.getId();
                        mLlSendComment.setVisibility(View.VISIBLE);
                        mEtCommentInput.requestFocus();
                        if (manager != null)
                            manager.showSoftInput(mEtCommentInput, InputMethodManager.SHOW_IMPLICIT);
                        break;
                    }
                    case R.id.tv_friend_dynamics_deletes: {
                        final BaseDialog dialog = new BaseDialog(HomePageActivity.this, R.layout.dialog_private, Gravity.CENTER, true);
                        ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("确定删除该动态?");
                        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("提示");
                        ((TextView) dialog.getView(R.id.btn_confirm)).setText("确定");
                        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.toggleDialog();
                            }
                        });
                        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.deleteDynamics(HomePageActivity.this, item.getId());
                                dialog.toggleDialog();
                            }
                        });
                        dialog.toggleDialog();
                        break;
                    }
                    case R.id.tv_dynamic_topic: {
                        Intent intent = new Intent(HomePageActivity.this, TopicDetailActivity.class);
                        intent.putExtra("id", item.getTid() + "");
                        startActivity(intent);
                        break;
                    }
                    case R.id.iv_friend_head: {
//                        Intent intent = new Intent(HomePageActivity.this, HomePageActivity.class);
//                        intent.putExtra("id", item.getUid() + "");
//                        startActivity(intent);
                        break;
                    }
                }
            }
        });

        mEtCommentInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    if (sendComment()) {
                        return false;
                    }

                    if (manager != null) {
                        manager.hideSoftInputFromWindow(textView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                        mEtCommentInput.clearFocus();
                    }
                    return true;
                }
                return false;
            }
        });

        mEtCommentInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (manager != null)
                        manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                }
            }
        });
        mFriendDynamicsAdapter.setOnCommentListener(new FriendDynamicsAdapter.onCommentListener() {
            @Override
            public void onCommentClick(int dynamicid, ReplyBean replyBean) {
                mDynamicsID = dynamicid;
                mCurReply = replyBean;
                mHostName = mCurReply.getUname();
                mEtCommentInput.setHint("@" + mHostName);
                mLlSendComment.setVisibility(View.VISIBLE);
                mEtCommentInput.requestFocus();
                if (manager != null)
                    manager.showSoftInput(mEtCommentInput, InputMethodManager.SHOW_IMPLICIT);
            }

            @Override
            public void onClickUser(String uid) {
                if (!mUid.equals(uid)) {
                    Intent intent = new Intent(HomePageActivity.this, HomePageActivity.class);
                    intent.putExtra("id", uid);
                    startActivity(intent);
                }
            }
        });
        mTvSendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sendComment()) {
                    return;
                }
                if (manager != null) {
                    manager.hideSoftInputFromWindow(mEtCommentInput.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                    mEtCommentInput.clearFocus();
                }
            }
        });
        mTvEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initKeyBoardListener() {
        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);
    }

    private boolean sendComment() {
        //这里写发送信息的方法
        String messge = mEtCommentInput.getText().toString();

        if (TextUtils.isEmpty(messge)) {
            ToastUtils.showToast("评论消息不能为空");
            return true;
        }

//                    String encodeMsg = null;
//                    try {
//                        encodeMsg = URLEncoder.encode(messge,"UTF-8");
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                        encodeMsg = messge;
//                    }
        if (mCurReply != null) {
//                        mPresenter.commentDynamics(DynamicDetailActivity.this,
//                                String.valueOf(mDynamicsID), String.valueOf(mCurReply.getId())
//                                , String.valueOf(mCurReply.getUid()), encodeMsg);
            mPresenter.commentDynamics(HomePageActivity.this,
                    1, String.valueOf(mDynamicsID), String.valueOf(mCurReply.getId())
                    , String.valueOf(mCurReply.getUid()), EmojiUtils.escape(messge));
        } else {
//                        mPresenter.commentDynamics(DynamicDetailActivity.this,
//                                String.valueOf(mDynamicsID), null, null, encodeMsg);
            mPresenter.commentDynamics(HomePageActivity.this,
                    0, String.valueOf(mDynamicsID), null, null, EmojiUtils.escape(messge));
        }

        hideReplyUser();
        clearEditText();
        return false;
    }

    private void clearEditText() {
        mEtCommentInput.setText("");
//        mEtComment.setText("");
    }

    private void hideReplyUser() {
        mCurReply = null;
        mHostName = null;
        mEtCommentInput.setHint("说点什么吧");
//        mEtComment.setHint("说点什么吧");
    }

    private void initRefreshLayout() {
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                tag = 1;
                page = page + 1;
                mPresenter.queryHomePage(HomePageActivity.this, mUid, page, dynamicType);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                requestDataForNetwork();
            }
        });
    }

    private void initView() {
        mRvFriendDynamics.setLayoutManager(new LinearLayoutManager(this));
//        mFriendDynamicsAdapter = new FriendDynamicsAdapter(getTestCourseList2());
        mFriendDynamicsAdapter = new FriendDynamicsAdapter(this, mDynamicsBeans, mUid);
        mRvFriendDynamics.setAdapter(mFriendDynamicsAdapter);
        if (!TextUtils.isEmpty(mUid) && mUid.equals(Constants.uid)) {
            rightImage.setVisibility(View.GONE);
            if (TextUtils.isEmpty(LocationHelper.getCity())) {
                mTvFriendAddress.setText("未知区域");
            } else {
                mTvFriendAddress.setText(LocationHelper.getmProvince() + LocationHelper.getCity());
            }
        } else {
            mTvFriendAddress.setVisibility(View.GONE);
            rightImage.setVisibility(View.VISIBLE);
            rightImage.setImageResource(R.mipmap.friend_more_icon);
        }

    }

    private void showPhotoDialog() {
        BottomPhotoDialog mBottomPhotoDialog = new BottomPhotoDialog(isBlack);
        mBottomPhotoDialog.setOnPhotoListener(new BottomPhotoDialog.OnPhotoListener() {
            @Override
            public void onClick(int id, String isBlack) {
                if (id == R.id.dialog_image_clicked_btn_delete) {
                    String message = "";
                    String title = "";
                    if ("0".equals(isBlack)) {
                        message = "你将不会再收到对方的评论和消息";
                        title = "将此人加入黑名单";
                    } else {
                        message = "你将继续收到对方的评论和消息";
                        title = "将此人移出黑名单";
                    }
                    new BlackListDialog(HomePageActivity.this, R.style.dialog,
                            message, new BlackListDialog.OnCloseListener() {
                        @Override
                        public void onClick(boolean confirm) {
                            if (confirm) {
//                                Toast.makeText(FriendPageActivity.this, "点击确定", Toast.LENGTH_SHORT).show();
                                mPresenter.deFriend(HomePageActivity.this, mUid);
                            }
                        }
                    }).setTitle(title).show();
                } else if (id == R.id.dialog_image_clicked_btn_report) {
//                    Toast.makeText(FriendPageActivity.this, "举报", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(HomePageActivity.this, ReportActivity.class);
                    intent.putExtra("uid", mUid);
                    intent.putExtra("name", nickname);
                    startActivity(intent);
                } else {

                }
            }
        });
        mBottomPhotoDialog.show(getSupportFragmentManager(), "photo");
    }

    @Override
    public void handleFailResponse(NetBean bean) {
        if ("1124".equals(bean.getRespCode())) {
            final BaseDialog dialog = new BaseDialog(HomePageActivity.this, R.layout.dialog_private, Gravity.CENTER, false);
            ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("不能访问对方主页");
            ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("提示");
            ((TextView) dialog.getView(R.id.btn_confirm)).setText("确定");
            dialog.getView(R.id.btn_cancel).setVisibility(View.GONE);
            dialog.getView(R.id.view_divider_bottom).setVisibility(View.GONE);
            dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.toggleDialog();
                    finish();
                }
            });
            dialog.toggleDialog();
        } else {
            super.handleFailResponse(bean);
        }
    }

    @Override
    public void getExpertDetail(JSONObject result) {
    }

    @Override
    public void getExpertDetail(DynamicListBean jsonObject) {
    }

    @Override
    public void getHomePage(HomePageBean jsonObject) {
        isBlack = jsonObject.getIsBlack();
        mTvFriendPraise.setText(jsonObject.getZanerNum() + "");
        final HomePageBean.NumMapBean numMap = jsonObject.getNumMap();
        if (numMap != null) {
            if (!TextUtils.isEmpty(numMap.getZanNum())) {
                mTvFriendPraised.setText(numMap.getZanNum());
            } else {
                mTvFriendPraised.setText("0");
            }
            if (!TextUtils.isEmpty(numMap.getComNum())) {
                mTvFriendComment.setText(numMap.getComNum());
            } else {
                mTvFriendComment.setText("0");
            }
        }
        final HomePageBean.UserMapBean userMap = jsonObject.getUserMap();
        if (userMap != null) {
            nickname = userMap.getNickname();
            mTvFriendName.setText(userMap.getNickname());
            if (TextUtils.isEmpty(userMap.getUseravatar())) {
                GlideUtils.loadImg(this, mIvFriendHead, R.mipmap.default_user_head);
            } else {
                GlideUtils.loadBackImg(this, mIvFriendHead, userMap.getUseravatar(), R.mipmap.default_user_head);
            }
        }
        final HomePageBean.DynamicBean dynamicBean = jsonObject.getP();
        final List<DynamicsBean> pageItems = dynamicBean.getPageItems();
        if (tag == 0) {  //刷新
            mRefreshLayout.setLoadmoreFinished(false);
            mRefreshLayout.finishRefresh();
            mDynamicsBeans.clear();
            if (pageItems.size() == 0) {
                mRlEmpty.setVisibility(View.VISIBLE);
            } else {
                mRlEmpty.setVisibility(View.GONE);
            }
        } else {  //加载更多
            mRefreshLayout.finishLoadmore();
        }
        mDynamicsBeans.addAll(pageItems);
        mFriendDynamicsAdapter.notifyDataSetChanged();
        //判断是否已到达最后一页，为true，将不会再次触发加载更多事件
        mRefreshLayout.setLoadmoreFinished(dynamicBean.getPageSize() * dynamicBean.getPageNumber() >= dynamicBean.getPageTotle());
    }

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (isShow) {
            mLlSendComment.setVisibility(View.VISIBLE);
            mEtCommentInput.requestFocus();
//            mRlDynamicsComment.setVisibility(View.GONE);
        } else {
            mLlSendComment.setVisibility(View.GONE);
//            mRlDynamicsComment.setVisibility(View.VISIBLE);
//            mEtComment.requestFocus();
            hideReplyUser();
//            String msg = mEtCommentInput.getText().toString();
//            mEtComment.setText(msg);
//            mEtComment.setSelection(msg.length());
        }
    }

    @Override
    public void followSportsSuccess(JSONObject jsonObject) {

    }

    @Override
    public void followDynamicsSuccess(JSONObject jsonObject) {
        mFriendDynamicsAdapter.setCellLikeState();
    }

    @Override
    public void deFriend(JSONObject jsonObject) {
        if ("0".equals(isBlack)) {
            ToastUtils.showToast("已拉黑");
        } else {
            ToastUtils.showToast("已移出黑名单");
        }
        requestDataForNetwork();
    }

    @Override
    public void deleteDynamicsSuccess(JSONObject jsonObject) {
        requestDataForNetwork();
    }

    @Override
    public void commentDynamicsSuccess(JSONObject result) {
        ToastUtils.showToast("发送评论成功");
        requestDataForNetwork();
    }
}
